<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 提示信息 -->
      <el-alert title="添加商品的信息"
                type="info"
                center
                show-icon
                :closable="false">
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200"
                :active="activeIndex - 0 "
                finish-status="success"
                align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="addForm"
               :rules="addFormrules"
               ref="addFormRef"
               label-width="100px"
               label-position="top">
        <!-- tab栏区域 -->
        <el-tabs :tab-position="'left'"
                 v-model="activeIndex"
                 :before-leave="beforeTabLeave"
                 @tab-click="tabClicked">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息"
                       name="0">
            <!-- 基本信息栏的表单数据 -->
            <el-form-item label="商品名称"
                          prop="goods_name"
                          status-icon>
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格"
                          prop="goods_price">
              <el-input v-model="addForm.goods_price"
                        type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量"
                          prop="goods_weight">
              <el-input v-model="addForm.goods_weight"
                        type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量"
                          prop="goods_number">
              <el-input v-model="addForm.goods_number"
                        type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类"
                          prop="goods_cat">
              <!-- 商品分类的级联选择器 -->
              <el-cascader v-model="addForm.goods_cat"
                           :options="cateList"
                           :props="cateProps"
                           @change="parentCateChanged"
                           clearable></el-cascader>
            </el-form-item>
            <!-- 基本信息栏的表单数据结尾 -->
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数"
                       name="1">
            <!-- 循环动态参数数组 -->
            <el-form-item :label="item.attr_name"
                          :key="item.attr_id"
                          v-for="item in manyTableData">
              <!-- 多选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <!-- 多选框 循环 vals得到详细参数 -->
                <el-checkbox :label="cb"
                             :key="i"
                             v-for="(cb,i) in item.attr_vals"
                             border>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!--  商品属性 -->
          <el-tab-pane label="商品属性"
                       name="2">
            <el-form-item :label="item.attr_name"
                          :key="item.attr_id"
                          v-for="item in onlyTableData">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片"
                       name="3">
            <!--
              action 图片上传后台的api地址
              on-preview 图片预览函数
              on-remove  移除图片
              list-type 组件渲染出来的ui效果  缩略图/列表/单纯 +号
             -->
            <el-upload class="upload-demo"
                       action="http://127.0.0.1:8888/api/private/v1/upload"
                       :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       list-type="picture"
                       :headers="headerObj"
                       :on-success="handleSuccess">
              <el-button size="small"
                         type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容"
                       name="4">
            <!-- 富文本编辑器
                          @blur="onEditorBlur($event)"
                          @focus="onEditorFocus($event)"
                          @ready="onEditorReady($event)"
                          :options="editorOption"   -->
            <quill-editor v-model="addForm.goods_introduce"
                          ref="myQuillEditor" />
            <br>
            <el-button type="primary"
                       @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

    </el-card>

    <!-- 预览图片对话框 -->
    <el-dialog title="图片预览"
               :visible.sync="previewVisible"
               width="50%">
      <img :src="previewPath"
           width="100%">
    </el-dialog>
  </div>
</template>>

<script>
import _ from 'lodash'

export default {
  data () {
    return {
      activeIndex: '0',
      //  添加商品的表单数据对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        //  商品所属的分类
        goods_cat: [],
        // 图片的相关数据
        pics: [],
        // 商品内容
        goods_introduce: '',
        // 动态参数以及静态属性的保存数组
        attrs: []
      },
      editorOption: '',
      //  基本信息的验证规则
      addFormrules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 选中的父级分类id数组
      selectedCateKeys: [],
      // 商品分类数据
      cateList: [],
      // 级联选择器的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 动态参数
      manyTableData: [],
      // 静态属性
      onlyTableData: [],
      // 图片上传的请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览对话框
      previewVisible: false,
      // 图片的真实路径
      previewPath: ''

    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      this.cateList = res.data
      console.log(this.cateList)
    },
    //  级联选择器选择了三级分类时触发
    parentCateChanged () {
      console.log({ 三级分类id: this.addForm.goods_cat })
      // 如果选择id 的长度不为三  证明没有选择三级分类
      if (this.addForm.goods_cat.length !== 3) {
        // 清空选中的数据即可
        this.addForm.goods_cat = []
      }
    },
    // 触发切换标签前发生的函数
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    // 点击tab栏切换标签时
    async tabClicked () {
      //  访问的时商品参数页面
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.$message.success('获取参数成功')
        this.manyTableData = res.data
        console.log(this.manyTableData)
      }
      //  访问的时商品属性页面
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')
        this.$message.success('获取参数成功')
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // 图片预览功能
    handlePreview (file) {
      this.previewVisible = true
      this.previewPath = file.response.data.url
    },
    // 移除图片
    handleRemove (file) {
      // 获取删除图片的保存路径
      const filePath = file.response.data.tmp_path
      // 根据路径findIndex 得到索引
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      // splice根据索引删除数组 pics对应的数据
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    //  上传图片成功调用的函数
    handleSuccess (response) {
      console.log(response)
      //  将响应回来的数据作为 pic对象添加到addForm表单pics数组中
      const picInfo = {
        pic: response.data.tmp_path
      }
      this.addForm.pics.push(picInfo)
      console.log(this.addForm)
    },
    // 添加商品
    add () {
      // 表单预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项！')

        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })

        // 深拷贝一个addForm表单进行  父级分类数组转换成 ，分割的字符串
        // 避免影响到级联选择器 因为他绑定的时一个数组而不是字符串
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        console.log(form)

        // 发送请求 添加商品
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 获取父级分类的id
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
</style>
